package com.mingtu.guards.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.hjq.gson.factory.GsonFactory;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.CenterPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.util.XPopupUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.GridSpacingItemDecoration;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.utils.SpacesItemDecoration;
import com.mingtu.common.view.ContainsEmojiEditText;
import com.mingtu.common.view.MultiGridView;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.DealRecordAdapter;
import com.mingtu.guards.adapter.PictureVideoVoiceAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.DealProcessBean;
import com.mingtu.guards.bean.ReportRecordDetailsBean;
import com.mingtu.guards.utils.MyConstant;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.guards.utils.MyConstant.MAX_ZOOM;

public class ReportedDetailsActivity extends MyBaseActivity {
    @BindView(R.id.mgv_lable)
    MultiGridView mgvLable;
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.rb_map1)
    RadioButton rbMap1;
    @BindView(R.id.rb_map2)
    RadioButton rbMap2;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.tvAddress)
    TextView tvAddress;
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_describe)
    TextView tvDescribe;
    @BindView(R.id.mgv_picture_video)
    RecyclerView recyclePictureVideo;
    @BindView(R.id.recycler_record)
    RecyclerView recycler;
    @BindView(R.id.but1)
    Button but1;
    @BindView(R.id.but2)
    Button but2;
    @BindView(R.id.layout_but)
    LinearLayout layoutBut;
    @BindView(R.id.layout_picture)
    LinearLayout layoutPicture;
    @BindView(R.id.layout_type)
    LinearLayout layoutType;
    @BindView(R.id.layout_process)
    LinearLayout layoutProcess;
    private String eventId;
    private ArrayList<LocalMedia> selectPictureList;
    private List<ReportRecordDetailsBean.EventUploadBean.EventAttachEntitiesBean> DataBean = new ArrayList<>();
    private PictureVideoVoiceAdapter pictureVideoVoiceAdapter;
    private AMap aMap;
    private List<Marker> markers = new ArrayList<>();
    private List<DealProcessBean.DealDataBean> dealData = new ArrayList<>();
    private DealRecordAdapter dealRecordAdapter;
    private Timer timer;
    private String sourceType;
    private String isReport;
    private String isDeal;
    private String createTime;
    private String solutionStr;
    private boolean isLeader = SPStaticUtils.getBoolean(SPTools.isLeader);
    private static final String[] mTitles = {"确认异常", "无异常"};
    private ArrayList<String> typeList = new ArrayList<>();
    private OptionsPickerView pvOptions;
    private int dealResult = 0;
    private TextView tvStatus;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_reported_details;
    }

    @Override
    protected void initView() {
        setModuleTitle("上报详情");
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recycler.setLayoutManager(linearLayoutManager);
        recycler.addItemDecoration(new SpacesItemDecoration(0, 0, 0, 0, 10));
    }

    @Override
    protected void initData() {


        dealRecordAdapter = new DealRecordAdapter(dealData);
        recycler.setAdapter(dealRecordAdapter);


        GridLayoutManager layoutManager = new GridLayoutManager(context, 3);//第二个参数为网格的列数
        recyclePictureVideo.setLayoutManager(layoutManager);
        recyclePictureVideo.addItemDecoration(new GridSpacingItemDecoration(3, SizeUtils.dp2px(15), false));

        pictureVideoVoiceAdapter = new PictureVideoVoiceAdapter(context, DataBean);
        recyclePictureVideo.setAdapter(pictureVideoVoiceAdapter);
        pictureVideoVoiceAdapter.setOnItemClickListener(new PictureVideoVoiceAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                BaseApplication.initPreviewModel().startActivityPreview(position, false, selectPictureList);
            }
        });

    }

    @Override
    protected void getData() {
        eventId = getIntent().getStringExtra("eventId");
        if (!StringUtils.isEmpty(eventId)) {
            getReportDetails();
        } else {
            ToastUtils.showLong("数据获取有误！");
        }
        if (isLeader) {
            layoutBut.setVisibility(View.VISIBLE);
        } else {
            layoutBut.setVisibility(View.GONE);

        }
        for (int i = 0; i < mTitles.length; i++) {
            typeList.add(mTitles[i]);
        }
        initOptionPicker();
    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        mapView = findViewById(com.mingtu.center.R.id.mapView);
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM_TWO));
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_map1:
                        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                        break;
                    case R.id.rb_map2:
                        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 矢量地图模式
                        break;
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁地图对象
        try {

            for (Marker marker : markers) {
                marker.remove();
            }

            if (timer != null) {
                timer.cancel();
            }

            if (aMap != null) {
                mapView.onDestroy();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.but1, R.id.but2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.but1:
                new XPopup.Builder(this)
                        .moveUpToKeyboard(true) //如果不加这个，评论弹窗会移动到软键盘上面
                        .isViewMode(true)
                        .asCustom(new CustomPopup(this))
                        .show();

//                auditEvent(1);
                break;
            case R.id.but2:
                new XPopup.Builder(this)
                        .dismissOnTouchOutside(true)
                        .hasShadowBg(true)
                        .asConfirm(context.getResources().getString(R.string.text_tip), "是否提交上级处理？",
                                context.getResources().getString(R.string.cancel), context.getResources().getString(R.string.sure),
                                new OnConfirmListener() {
                                    @Override
                                    public void onConfirm() {
                                        auditEvent(2);
                                    }
                                }, null, false)
                        .show();

                break;
        }
    }


    /**
     * 查询上报事件的详情
     */
    private void getReportDetails() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", eventId);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_EVENT_DETAILS + "/" + eventId)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            ReportRecordDetailsBean.EventUploadBean eventUploadBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                ReportRecordDetailsBean reportRecordDetailsBean = new ReportRecordDetailsBean();
                                reportRecordDetailsBean = gson.fromJson(result, ReportRecordDetailsBean.class);

                                eventUploadBean = reportRecordDetailsBean.getEventUpload();
                                //"yes" 拥有上报权限(站长拥有) "no" 没有上报权限
                                isReport = eventUploadBean.getIsReport();
                                isDeal = eventUploadBean.getIsDeal();
//                                String status = eventUploadBean.getStatus(); //status =0是上报等待站长审批，status=1 站长上报给局长，status=2结束
                                DataBean = eventUploadBean.getEventAttachEntities();

                                selectPictureList = new ArrayList<>();
                                layoutPicture.setVisibility(View.GONE);
                                if (DataBean != null) {
                                    if (DataBean.size() > 0) {
                                        layoutPicture.setVisibility(View.VISIBLE);
                                    }
                                }

                                for (int i = 0; i < DataBean.size(); i++) {
                                    String url = DataBean.get(i).getAttachUrl();
                                    LocalMedia localMedia = LocalMedia.generateHttpAsLocalMedia(url);
                                    selectPictureList.add(localMedia);
                                }

                                pictureVideoVoiceAdapter.upData(DataBean);

                                String eventCode = eventUploadBean.getEventCode();
                                createTime = eventUploadBean.getCreateTime();
                                String address = eventUploadBean.getAddress();
                                String eventDesc = eventUploadBean.getEventDesc();
                                String tag = eventUploadBean.getTag();
                                String lat = eventUploadBean.getLat();
                                String lng = eventUploadBean.getLng();

                                if (!StringUtils.isEmpty(lng) && !StringUtils.isEmpty(lat)) {
                                    LatLng location = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
                                    //添加Marker
                                    MarkerOptions markerOptions = new MarkerOptions()
                                            .position(location)
                                            .icon(BitmapDescriptorFactory.fromResource(com.mingtu.center.R.mipmap.sb_icon_wz));
                                    Marker marker = aMap.addMarker(markerOptions);
                                    markers.add(marker);
                                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
                                }

                                //列表显示，说明已经有数据，不用再判空
                                tvCode.setText(eventCode + "");
                                tvTime.setText(createTime + "");
                                tvAddress.setText(address + "");
                                tvDescribe.setText(eventDesc + "");


                                if (!StringUtils.isEmpty(tag)) {
                                    tvType.setText(tag + "");
                                    layoutType.setVisibility(View.VISIBLE);
                                    layoutProcess.setVisibility(View.VISIBLE);
                                } else {
                                    layoutType.setVisibility(View.GONE);
                                    layoutProcess.setVisibility(View.GONE);
                                }


                                String name = eventUploadBean.getName();
                                List<ReportRecordDetailsBean.EventUploadBean.EventUploadDetailEntityListBean> entityListBeans =
                                        eventUploadBean.getEventUploadDetailEntityList(); //处理流程

                                Collections.reverse(entityListBeans); //逆序排列


                                List<HashMap<String, Object>> dealData = new ArrayList<>();
                                HashMap<String, Object> itemDeal = new HashMap<>(); //普工人员上报
                                itemDeal.put("dealTime", createTime);
                                itemDeal.put("dealInfo", "【" + name + "】" + "上报了异常事件");
                                dealData.add(itemDeal);


                                if (entityListBeans != null && entityListBeans.size() > 0) {
                                    int size = entityListBeans.size();
                                    if (size == 1) {
                                        ReportRecordDetailsBean.EventUploadBean.EventUploadDetailEntityListBean entityListBean =
                                                entityListBeans.get(0);
                                        HashMap<String, Object> itemDea2 = new HashMap<>(); //普工人员上报
                                        itemDea2.put("dealTime", entityListBean.getAuditTime());
                                        itemDea2.put("dealInfo", "【" + entityListBean.getUserName() + "】" + "处理了异常事件");
                                        dealData.add(itemDea2);
                                    } else {
                                        for (int i = 0; i < entityListBeans.size(); i++) {
                                            ReportRecordDetailsBean.EventUploadBean.EventUploadDetailEntityListBean entityListBean =
                                                    entityListBeans.get(i);
                                            HashMap<String, Object> itemDeal2 = new HashMap<>();
                                            itemDeal2.put("dealTime", entityListBean.getAuditTime());
                                            if (i == size - 1) {
                                                itemDeal2.put("dealInfo", "【" + entityListBean.getUserName() + "】" + "处理了异常事件");
                                            } else {
                                                itemDeal2.put("dealInfo", "【" + entityListBean.getUserName() + "】" + "提交了上级处理");
                                            }
                                            dealData.add(itemDeal2);
                                        }
                                    }
                                }

                                Collections.reverse(dealData); //逆序排列

                                HashMap<String, Object> hashMap = new HashMap<>();
                                hashMap.put("dealData", dealData);
                                String str = GsonUtils.toJson(hashMap);

                                DealProcessBean dealProcessBean = new DealProcessBean();
                                dealProcessBean = gson.fromJson(str, DealProcessBean.class);

                                List<DealProcessBean.DealDataBean> dealDataBeans = dealProcessBean.getDealData();
                                dealRecordAdapter.upData(dealDataBeans);

                                if (isReport.equals("yes")) {
                                    but2.setVisibility(View.VISIBLE);
                                } else {
                                    but2.setVisibility(View.GONE);
                                }

                                if (isDeal.equals("yes")) {
                                    but1.setVisibility(View.VISIBLE);
                                } else {
                                    but1.setVisibility(View.GONE);
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }


                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });

    }

    /**
     * 审批上报事件
     */
    private void auditEvent(int type) {
        //处理类型1：结束2：继续上报
        but1.setVisibility(View.GONE);
        but2.setVisibility(View.GONE);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", eventId);
        hashMap.put("type", type);

        if (type == 1) {
            hashMap.put("dealResult", dealResult);
            hashMap.put("memo", solutionStr);
        }

        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_AUDIT_EVENT)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                String str = "";
                                if (type == 1) {
                                    str = "处理完成！";
                                } else if (type == 2) {
                                    str = "提交成功！";
                                }
                                ToastUtils.showLong(str);

                                //实例化Timer类 ,守护线程，不在后台一直运行
                                timer = new Timer(true);
                                timer.schedule(new TimerTask() {
                                    public void run() {
                                        setResult(200);
                                        EventBus.getDefault().post(new MyEventBus(MyConstant.REFRESH_REPORTED_DATA));
                                        ActivityUtil.removeActivity(ReportedDetailsActivity.this);
                                    }
                                }, Constant.TIMER_TIME);


                            } else {
                                String str = "";
                                if (type == 1) {
                                    str = "处理失败！";

                                } else if (type == 2) {
                                    str = "提交失败！";
                                }
                                ToastUtils.showLong(str);
                                if (!StringUtils.isEmpty(isReport)) {
                                    if (isReport.equals("yes")) {
                                        but2.setVisibility(View.VISIBLE);
                                    } else {
                                        but2.setVisibility(View.GONE);
                                    }
                                }
                                if (!StringUtils.isEmpty(isDeal)) {
                                    if (isDeal.equals("yes")) {
                                        but1.setVisibility(View.VISIBLE);
                                    } else {
                                        but1.setVisibility(View.GONE);
                                    }
                                }
                            }
                        }
                    }
                });
    }

    private class CustomPopup extends CenterPopupView {
        //注意：自定义弹窗本质是一个自定义View，但是只需重写一个参数的构造，其他的不要重写，所有的自定义弹窗都是这样。

        public CustomPopup(@NonNull Context context) {
            super(context);
        }

        // 返回自定义弹窗的布局
        @Override
        protected int getImplLayoutId() {
            return R.layout.layout_solution;
        }

        // 执行初始化操作，比如：findView，设置点击，或者任何你弹窗内的业务逻辑
        @Override
        protected void onCreate() {
            super.onCreate();

            Button butSubmit = findViewById(R.id.but_submit);
            tvStatus = findViewById(R.id.tv_status);
            ContainsEmojiEditText editSolution = findViewById(R.id.edit_solution);
            editSolution.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    MyLogUtil.e("MyTest", "afterTextChanged==" + s.toString());
                    solutionStr = MyUtills.getEditText(editSolution);
                    editSolution.setSelection(solutionStr.length());
                }
            });


            butSubmit.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss(); // 关闭弹窗
                    auditEvent(1);
                }
            });
            tvStatus.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    pvOptions.show();
                }
            });
        }

        @Override
        protected void onDismiss() {
            KeyboardUtils.hideSoftInput(ActivityUtil.getTopActivity());
        }

        @Override
        protected int getMaxHeight() {
            return (int) (XPopupUtils.getScreenHeight(getContext()) * .7f);
        }
    }

    /**
     * 条件选择器
     */

    private void initOptionPicker() {//条件选择器初始化

        pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                dealResult = options1;
                String type = typeList.get(options1);
                tvStatus.setText(type);
            }
        })

                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(getResources().getColor(R.color.black_eee))
                .setCancelColor(getResources().getColor(R.color.text_cancel_color))
                .setSubmitColor(getResources().getColor(R.color.text_submit_color))
                .setTextColorCenter(getResources().getColor(R.color.colorPrimary))
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .setOutSideColor(getResources().getColor(R.color.translucence)) //设置外部遮罩颜色
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {

                    }
                })
                .build();

        pvOptions.setSelectOptions(dealResult);
        pvOptions.setPicker(typeList);//进入页面就获取，默认不显示
    }


}